package pay

import (
	"OnlineRetailers/models"
	USER "OnlineRetailers/models/User"
	PAY "OnlineRetailers/models/pay"
	"fmt"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
)

func pay(openid string, order *USER.Order) (err error, resp *jsapi.PrepayWithRequestPaymentResponse) {

	var money int64
	money = int64((order.Money * 100) / 1)
	name := order.OrderCart[0].Product.Name + "等商品"

	svc := jsapi.JsapiApiService{Client: PAY.Client}
	// 得到prepay_id，以及调起支付所需的参数和签名
	resp, _, err = svc.PrepayWithRequestPayment(PAY.Ctx,
		jsapi.PrepayRequest{
			Appid:       core.String(models.AppId),
			Mchid:       core.String(models.Mchid),
			Description: core.String(name),
			OutTradeNo:  core.String(order.OrderId),
			Attach:      core.String("自定义数据说明"),
			NotifyUrl:   core.String("https://www.weixin.qq.com/wxpay/pay.php"),
			Amount: &jsapi.Amount{
				Total: core.Int64(money),
			},
			Payer: &jsapi.Payer{
				Openid: core.String(openid),
			},
		},
	)
	if err != nil {
		fmt.Println(err)
		return err, nil
	}
	fmt.Println(resp)
	return nil, resp
}

func findPay(orderId string) (err error, resp *payments.Transaction) {

	svc := jsapi.JsapiApiService{Client: PAY.Client}

	resp, _, err = svc.QueryOrderById(PAY.Ctx,
		jsapi.QueryOrderByIdRequest{
			TransactionId: core.String(orderId),
			Mchid:         core.String(models.Mchid),
		},
	)
	if err != nil {
		fmt.Println(err)
		return err, nil
	}

	//fmt.Println(resp)
	return nil, resp
}
